using Character;
using UnityEngine;

public class GroundDetectComponent : CharacterComponent
{
    private static LayerMask groundMask;
    private static LayerMask GroundMask
    {
        get
        {
            if(groundMask == default)
                groundMask = LayerMask.GetMask("Ground");
            return groundMask;
        }
    }

    [SerializeField]
    private float groundedDistance = 1f;
    public float maxDistance = 20f;
    public Vector3[] detectPoints;

    [SerializeField]
    private float distanceToGround;
    public float DistanceToGround => distanceToGround;
    public bool Grounded => distanceToGround < groundedDistance;

    private void Update()
    {
        DetectDistance();
    }

    public float DetectDistance()
    {
        float Detect(Vector3 point)
        {
            bool flag = Physics.Raycast(point, Vector3.down, out RaycastHit hit, maxDistance, GroundMask);
            return flag ? hit.distance : maxDistance;
        }

        float min = maxDistance;
        for (int i = 0; i < detectPoints.Length; i++)
        {
            min = Mathf.Min(Detect(transform.position + detectPoints[i]), min);
        }
        distanceToGround = min;
        return min;
    }

    private void OnDrawGizmos()
    {
        for (int i = 0; i < detectPoints.Length; i++)
        {
            Vector3 point = transform.position + detectPoints[i];
            bool flag = Physics.Raycast(point, Vector3.down, groundedDistance, GroundMask);
            Gizmos.color = flag ? Color.red : Color.green;
            Gizmos.DrawLine(point, point + groundedDistance * Vector3.down);
        }
    }
}
